package com.leetcode.algorithm.y22.m08.w2;

/**
 * 209. 长度最小的子数组
 * 
 * https://leetcode.cn/problems/minimum-size-subarray-sum/
 * 
 * @author jie.deng
 *
 */
class Question0209Solution02 {

	public int minSubArrayLen(int target, int[] nums) {
		// 滑动窗口
		int len = nums.length;
		// Step 1: 定义需要维护的变量
		int sum = 0;
		int minLen = len + 1;
		// Step 2: 定义窗口的首尾端 (left, right)， 然后滑动窗口
		int left = 0;
		// [left, right] sum(left...right) >= target
		for (int right = 0; right < len; right++) {
			sum += nums[right];
			while (sum >= target) {
				// Step 3: 需要改变左索引的情况：改变左索引前，更新需要维护的变量
				minLen = Math.min(minLen, right - left + 1);
				sum -= nums[left];
				left++;
			}
			// Step 4: 改变右索引
		}
		// Step 5: 返回答案
		return (minLen == len + 1) ? 0 : minLen;
	}

}